﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Meteoric.Page;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Shanbay.Core;
using Shanbay.Model;

namespace Shanbay.Page
{
    public class AddWord: ShanbayPage
    {
        private string err = "";
        public int status;
        private ShanbayUrl shanbayUrl;
        protected override void InitPage()
        {
            
            string str = Request.ToStr("action");
            shanbayUrl = new ShanbayUrl();
            switch (str)
            {
                case "addword":
                    if (AddWords())
                    {
                        JObject a = new JObject
                        {
                            {"success", "true"},
                            { "msg", "成功"}
                        };
                        Response.Write(a.ToString());
                    }
                    else
                    {
                        JObject a = new JObject {{"success", "false"}, {"msg", err}};
                        Response.Write(a.ToString());
                    }
                    break;
            }
        }
       
        

         bool AddWords()
        {
            string word = Request.ToStr("word");
            //获取Id
            string result = shanbayUrl.GetWordId(GetToken().Token,word);
            if (string.IsNullOrEmpty(result))
            {
                err = shanbayUrl.Err;
                return false;
            }
            var r = JsonConvert.DeserializeObject<SRet>(result);
            if (r.status_code != 0)
            {
                err = String.Format("获取单词id失败,错误:{0},错误代码:{1}", r.msg, r.status_code);
                status = r.status_code;
                return false;
            }
            //添加单词
            result =  shanbayUrl.PostWord(GetToken().Token,r.data.id);
             if (string.IsNullOrEmpty(result))
             {
                 err += shanbayUrl.Err;
                 return false;
             }
             r = JsonConvert.DeserializeObject<SRet>(result);
            if (r.status_code != 0)
            {
                err = "添加单词失败,错误:" + r.status_code;
                return false;
            }
             return true;
        }
        
        
    }
}
